/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  ToolbarAndroid,
  Dimensions,
  ListView,
  DeviceEventEmitter,
  Platform,
  TouchableHighlight,
  NativeModules,
} from 'react-native';
import {CachedImageBackground} from "react-native-img-cache";
import Common from '../../../component/common';
import ScreenUtils from '../../../component/ScreenUtils';
import Toast from 'react-native-root-toast';
import Article from '../../home/article';


const wechat=require('../../../images/wechat.png');
const weibo=require('../../../images/weibo.png');
const web=require('../../../images/newspaper.png');



const totalWidth = Dimensions.get('window').width;

export default class newsItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
  		showDeleteButton: this.props.showDeleteButton,
  		rows:this.props.data.list,
  		sectionTitle: this.props.data.typeName,
  		classType:this.props.classType,
  		showTitle:this.props.showTitle,
      	deleteArr:[],
      	dataLength:this.props.data.list.length,
   };
   this.showTitle=this.state.showTitle;
   this.selectArr=[];
   this.openScroll=[]
  }
  
  componentWillUnmount() {
  	//this.noDataEvent.remove();
  }
  componentWillReceiveProps(nextProps){
  	if(parseInt(nextProps.classType) == 4 && nextProps.data.list != this.state.rows) {
      this.setState({
        rows:nextProps.data.list,
        dataLength:nextProps.data.list.length,
        showTitle:nextProps.showTitle,
        deleteArr:[]
      })
      this.selectArr=[];
      this.showTitle=this.state.showTitle;
    } 
    if(this.openScroll.length>0){
      this.openScroll.map((item,key)=>{
          item.scrollTo({ x: 0, y: 0, animated: false });
          this.openScroll=[]
      })
    }
  }
  componentDidMount(){
  	
  }
  render() {
  	let propDataLength = this.state.rows.length;
  	if(propDataLength===0){
  		return null;
  	}else{
		return(
			<View style={styles.collectionColumn}>
				{
      				this.state.showTitle?　
      					<Text style={styles.collectionCategory}>
      						{this.state.sectionTitle}
      						{
      							this.props.totalPage ? <Text>({String(this.props.totalPage)})</Text> :null
      						}
      					</Text>　: null
      			}
	      		<View style={styles.item}> 
		          	{
			            this.state.rows.map((item,key)=>{
			              return this.renderInfoItems(item,key)
			            })
		          	}
				</View>
			</View>
		)  
	}
  }
  
  handleDelete(rowIndex,entityId,target){
  	let formData = new FormData();
	formData.append("entityId",entityId);
	formData.append("userToken",this.props.userToken);
	Common.fetchData("POST", "/userCenter/collect/delete", formData, (responseData) => {
    let isShowTitle=this.state.dataLength;
    let showTitle = isShowTitle==1 ? false :true;
    if(isShowTitle==1){
      DeviceEventEmitter.emit("noData",null);
    }
		this.selectArr.push(entityId);
      this.setState({
        deleteArr:this.selectArr,
        dataLength:isShowTitle-1,
        showTitle:showTitle
      });
      
      target.scrollTo({x: 0, y: 0, animated: false});
		Toast.show("删除成功",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("删除失败",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("网络错误",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	});
  }
  showDeleteButton(ev,target){
  	if(this.startLocation>this.moveLocation){
  		target.scrollToEnd({animated: true});
      this.openScroll.push(target);
  	}else{
  		target.scrollTo({x:0,y:0,animated: true});
  	}
  }
  linking(val) {
    if(Platform.OS == 'ios'){
      NativeModules.JsAndroid.openUrl(val.url);
    }else{
      // Common.onForward(this, Article, val, 5);
      Common.onForward(this.props.chageThis,Article,val,4)
    }
  }
  renderInfoItems(data,rowID) {
  	var _scrollView: ScrollView;
  	let sourceImage;
  	var mydata = Common.keyWordHighlight(data.title);
  	switch(data.scrabbleType){
  		case 'wechat':
  			sourceImage = wechat;
  			break;
  		case 'web':
  			sourceImage = web;
  			break;
  		default :
  			sourceImage = weibo;
  			break;
  	}
  	var vMarginBottom=ScreenUtils.scaleSize(0);
  	var Vheight = ScreenUtils.scaleSize(176);
    this.state.deleteArr.map((item,key)=>{
      if(item==data.id){
        Vheight=0;
        vMarginBottom=0;
      }
    })
    return (
    <ScrollView
      	horizontal = {true}
      	showsHorizontalScrollIndicator = {false}
      	ref={(scrollView) => { _scrollView = scrollView; }}
      	onTouchStart={(event)=>{
      		this.startLocation=event.nativeEvent.pageX
      	}}
      	onTouchMove={(event)=>{
      		this.moveLocation=event.nativeEvent.pageX
      	}}
      	onScrollEndDrag={(event)=>{
      		 this.showDeleteButton(event,_scrollView);
      	}}
      	contentContainerStyle={{marginBottom:vMarginBottom,height:Vheight,overflow:"hidden"}}
        key={rowID}
      >
	  	<TouchableHighlight 
	      	style={styles.newListWrap} 
	      	underlayColor="#fafafa" 
	      	delayPressIn={100} 
	      	onPress={() => this.linking({title:Common.cancelHightlight(data.title),url:data.url,id:data.id})}
	      >
	        <View style={styles.newsListItem}>
	          <View style={styles.newsText}>
	            <Text style={styles.newsTitle} numberOfLines ={2}>{data.title}</Text>
	            <View style={styles.newsSource}>
	            	<View style={styles.newsAout}>
	            		<Image style={styles.infoAboutImage} source = {sourceImage}/>
	            		<Text style={styles.infoAboutText}>{data.company}</Text>
	            	</View>
	            	<View style={styles.newsAout}>
	            		<Image style={styles.infoAboutImageTimer} source = {require('../../../images/timer.png')}/>
	            		<Text style={styles.infoAboutText}>{Common.beforeTime(data.subcribeTime,5)}</Text>
	            	</View>
	            	{
	            		data.clickCount ? 
	            		<View style={styles.newsAout}>
		            		<Text style={styles.infoAboutText}>{data.clickCount}</Text>
		            		<Text style={styles.infoAboutText}>阅读</Text>
		            	</View> :null
	            	}
	            	
	            </View>
	          </View>
	          {
	          	data.img || data.img != "" ?
	          	<View style={styles.newsPic}>
	            	<CachedImageBackground style={styles.newsAboutPic} source ={{uri:data.img}}/>
	          	</View> : <View style={[styles.newsPic,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
	          }
	          
	        </View>
	    </TouchableHighlight>
     	{
	      	this.state.showDeleteButton ?
		      (
		      	<TouchableOpacity 
		      		style={styles.deleteWrap} 
		      		onPress={()=>{
		      			this.handleDelete(rowID,data.id,_scrollView)
		      			}
		      		}
		      	>
			      <Text style={styles.deleteText}>删除</Text>
			    </TouchableOpacity>
		      ):null
	    }
    </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  newListWrap:{
  	width:totalWidth,
  	paddingVertical:ScreenUtils.scaleSize(24),
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(26),
  	borderBottomWidth:1,
    flexDirection:"row",
    borderColor:"#ebebeb",
    backgroundColor:"#fff",
  },
  newsListItem:{
  	flex:1,
    height:ScreenUtils.scaleSize(128),
    flexDirection:"row",
    justifyContent:'space-between',
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  newsText:{
  	flex:1,
  	height:ScreenUtils.scaleSize(128),
  	paddingRight:ScreenUtils.scaleSize(36),
  	flexDirection:"column",
  	justifyContent:'space-between',
  },
  newsPic:{
  	width:ScreenUtils.scaleSize(190),
  	height:ScreenUtils.scaleSize(128),
  	justifyContent:'center',
  	alignItems:'center'
  },
  newsAboutPic:{
  	width:ScreenUtils.scaleSize(190),
  	height:ScreenUtils.scaleSize(128),  	
  },
  newsTitle:{
  	fontSize:ScreenUtils.scaleSize(24),
    lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  	color:"#4d4d4d",
  },
  newsSource:{
  	flexDirection:"row",
  	justifyContent:'flex-end',
  },
  newsAout:{
  	flexDirection:"row",
  	marginLeft:5,
  	justifyContent:"center",
  	alignItems:"center",
  },
  infoAboutImage:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(18),
  	resizeMode: 'contain',
  },
  infoAboutImageTimer:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(22),
  },
  infoAboutText:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#9d9d9d",
  	paddingLeft:3,	
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
  	paddingBottom:ScreenUtils.scaleSize(14),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  Item:{
  	marginTop:ScreenUtils.scaleSize(14),
  	borderColor:"#ebebeb",
  },
  showMore:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor:'#fff',
  	borderBottomWidth:1,
  	borderColor:'#ebebeb',
  	flexDirection:"row",
  },
  seperatorCell:{
  	marginTop:-ScreenUtils.scaleSize(14)/2,
  	zIndex:-5,
  }
});